//
//  AppDelegate.swift
//  Weibo
//
//  Created by Northwan on 16/1/19.
//  Copyright © 2016年 Northwan. All rights reserved.
//

import UIKit
import SVProgressHUD

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var observer:NSObjectProtocol?//注意

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        SVProgressHUD.setBackgroundColor(UIColor(white: 1, alpha: 0.5))
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // 设置根控制器
        window?.rootViewController = NWUserAccountViewModel.sharedAccount.userLogon ? defaultRootViewController() : NWMainViewController()
        window?.makeKeyAndVisible()
        
        
        //切换根控制器的通知
        observer =  NSNotificationCenter.defaultCenter().addObserverForName(kSwithRootCtrlNortif, object: nil, queue: nil) {[weak self] (nortif) -> Void  in
            if nortif.object is NWOauthViewController {
                self?.window?.rootViewController = NWWelcomeViewController()
            }else{
                self?.window?.rootViewController = NWMainViewController()
            }
        }
        return true
    }
    
    func defaultRootViewController()->UIViewController{
        //判断是不是第一次安装
        if hasNewVersion() {
            return NWNewFeatureViewController()
        }else{
            return NWWelcomeViewController()
        }
    }
    
    func hasNewVersion() -> Bool {
        
        let preVersion = NSUserDefaults.standardUserDefaults().stringForKey("version")
        
        let currentVersion = NSBundle.mainBundle().infoDictionary?["CFBundleShortVersionString"] as? String
        
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: "version")
        // 如果沙盒里面的版本号不小于当前版本号，就代表没有新版本
        if let result = preVersion where result.compare(currentVersion!) != NSComparisonResult.OrderedAscending{
            return false
        }
        return true
    }

    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(observer!)
    }

}

